package com.test;

/**
 * @Description:单链表
 * @Auther: liuyanhui
 * @Date: 2024/03/12/ 14:53
 */
public class SinglyLinkedList {
    private ListNode head;

    public void insert(int value) {
        if (head == null) {
            head = new ListNode(value);
            return;
        } else {
            ListNode current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = new ListNode(value);
        }
    }

    private boolean delete(int value) {
        if (head == null) {
            return false;
        }
        if (head.val == value) {
            head = head.next;
            return true;
        }
        ListNode current = head;
        while (current.next != null) {
            if (current.next.val == value) {
                current.next = current.next.next;
                return true;
            }
            current = current.next;
        }
        return false;
    }

    public void reverse() {
        ListNode current = head;
        ListNode pre = null;
        while (current != null) {
            ListNode next = current.next;
            current.next = pre;
            pre = current;
            current = next;
        }
        head = pre;
    }

    public static void main(String[] args) {
        SinglyLinkedList singlyLinkedList = new SinglyLinkedList();
        singlyLinkedList.insert(1);
        singlyLinkedList.insert(2);
        singlyLinkedList.insert(3);
        singlyLinkedList.insert(4);
        singlyLinkedList.reverse();
        while (singlyLinkedList.head != null) {
            System.out.println(singlyLinkedList.head.val);
            singlyLinkedList.head = singlyLinkedList.head.next;
        }
    }

    // 实现两个有序的链表合并为一个有序链表
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(0);
        ListNode pre = dummyHead;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                pre.next = l1;
                l1 = l1.next;
            } else {
                pre.next = l2;
                l2 = l2.next;
            }
        }
        pre.next = l1 == null ? l2 : l1;
        return dummyHead.next;
    }

    // 实现求链表的中间结点
    public static ListNode middleNode(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

}
